package br.com.q7solucoes.parsercinemaq7;

import br.com.q7solucoes.parsercinemaq7.URLParser.URLType;
import br.com.q7solucoes.commons.wordpress.WPPost;
import br.com.q7solucoes.commons.wordpress.WPPostDAO;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Thread para fazer o parse de um endereco e ja faz a persistencia.
 *
 * @author Elenilson Vieira - elenilson[at]q7solucoes.com.br
 * @since 13 de setembro 2011
 * @version 1.0
 * @see www.q7solucoes.com.br
 */
public class URLParserThread extends Thread{

    private String url;
    private URLType uRLType;
    private WPPostDAO wPPostDAO;
    private Exception error;
    private boolean replicate;

    public URLParserThread(String url, URLType uRLType, WPPostDAO wPPostDAO, boolean replicate) {
        this.url = url;
        this.uRLType = uRLType;
        this.wPPostDAO = wPPostDAO;
        this.replicate = replicate;
    }

    public URLParserThread(URLType uRLType, WPPostDAO wPPostDAO, boolean replicate) {
        this(null, uRLType, wPPostDAO, replicate);
    }

    public void run(){
        try{
            URLParser parser = new URLParser(uRLType, url);
            WPPost post = parser.parse();
            
            wPPostDAO.add(post);
            String originalLink = post.getLink();
            
            if(replicate){
                Calendar now = GregorianCalendar.getInstance();
                now.setTime(post.getDate());
                
                int i = 1;
                while(now.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY){
                    now.add(Calendar.DAY_OF_YEAR, 1);
                    
                    post.setDate(now.getTime());
                    post.setLink(originalLink + "-" + i++);
                    wPPostDAO.add(post);
                }
            }
        }catch(Exception ex){
            error = ex;
            ex.printStackTrace();
        }
    }

    public Exception getError() {
        return error;
    }

    public URLType getuRLType() {
        return uRLType;
    }

    public String getUrl() {
        return url;
    }

    public WPPostDAO getwPPostDAO() {
        return wPPostDAO;
    }

}
